package com.chazz.servlet;

import com.chazz.Do.GoodsInfo;
import com.chazz.utils.JSONUtils;
import com.chazz.utils.TotalPriceUtils;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/discount.do")
public class DiscountServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * description: doPost 计算折扣价格接口 <br> version: 1.0 <br> date: 2020/9/23 21:31 <br> author: Chazz
     * <br>
     *
     * @param req
     * @param resp
     * @return void
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        resp.setContentType("application/json; charset=UTF-8");
        //获取前端购物车商品信息
        String goods = req.getParameter("goods");
        System.out.println(goods);
        //通过JSON工具类将前端数据分装为对象数组
        List<GoodsInfo> goodsInfos = JSONUtils.toList(GoodsInfo.class, goods);
        System.out.println(goodsInfos);
        Double totalPrice = 0.0;
        //循环遍历计算每个商品折后的价格
        for (GoodsInfo goodsInfo : goodsInfos) {
            totalPrice += new TotalPriceUtils().count(goodsInfo);
        }
        //用DecimalFormat("#.00");方式将double类型的价格格式化到小数点后两位
        DecimalFormat df = new DecimalFormat("#.00");
        String totalPriceStr = df.format(totalPrice);
//      String s = totalPriceStr.substring(0,totalPriceStr.indexOf(".") + 3);
        System.out.println(totalPriceStr);
        resp.getWriter().write(totalPriceStr);
//        req.setAttribute("totalPrice", totalPriceStr);
//        req.getRequestDispatcher("").forward(req, resp);
    }
}
